<?php

namespace app\index\controller;

use app\BaseController;
use app\IndexBaseController;
use think\facade\Db;
use think\facade\fetch;
use think\App;
use think\facade\View;

class Order extends IndexBaseController
{
    //继承
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        return View::fetch('index');
    }
	
    public function cartList() {
        //购物车列表数据
        $goodslists = Db::name('shopping_trolley')->alias('a')
            ->field('a.num,b.*')
            ->leftJoin('goods b','a.goods_id=b.id')
            ->where(['a.deleted'=>0])->select()->toArray();
        return $this->success($goodslists);
    }

    //购物车结算
    public function shoppingCart() {
        $user = $this->_user;
        $param = $this->_param;
        $time = time();
        $type = 1;
        //查询购物车数据
        if($user['is_wholesale'] == 1) {
            $type = 2;
            //批发商
            $goods_list = Db::name("shopping_trolley")->alias('a')
                ->field("a.goods_id,a.num,b.*,b.wholesale_price money")
                ->leftJoin('goods b','a.goods_id=b.id')
                ->where(['a.user_id'=>$user['id'],'a.deleted'=>0])->select()->toArray();

        }else {
            //普通用户
            $goods_list = Db::name("shopping_trolley")->alias('a')
                ->field("a.goods_id,a.num,b.*,b.price money")
                ->leftJoin('goods b','a.goods_id=b.id')
                ->where(['a.user_id'=>$user['id'],'a.deleted'=>0])->select()->toArray();
        }

        $weight = 0;//kg
        $pay_money = 0;
        $num = 0;
        foreach ($goods_list as $k=>$v) {
            if($v['stock'] < $v['num']) {
                return $this->error($v['name']." understock");
            }
            //计算重量-运费
            $weight = $weight + $v['unit_weight']*$v['num'];
            //计算金额
            $pay_money = $pay_money + $v['money']*$v['num'];
            //计算数量
            $num = $num + $v['num'];
        }
        //运费
        $freight = Db::name('freight')->where('weight','<',$weight)->where(['deleted'=>0])->limit(1)->order('weight desc')->value("money");
        if(!$freight) {
            $freight = 0;
        }
        $total_money = $pay_money + $freight;

        $order = [
            'origin' => 1,
            'sub_money' => $pay_money,
            'money' => $total_money,
            'delivery_money' => $freight,
            'state' => 1,//订单状态 1未付款,2已付款,3已接单,4配送中/待取货,5已收货,6已评价,7已取消,8.拒单，9申请退款,10已退款，11退款拒绝
            'user_id' => $user['id'],
            'create_time' => $time,
            'update_time' => $time,
        ];
        //商品处理
        $order_goods_list = [];
        foreach ($goods_list as $k=>$v) {
            $order_goods_list[] = [
                'goods_id' => $v['goods_id'],
                'name' => $v['name'],
                'icon' => $v['icon'],
                'price' => $v['money'],
                'num' => $v['num'],
                'money' => $v['money'] * $v['num'],
                'type' => $type,
                'create_time' => $time,
                'update_time' => $time,
            ];
        }
        $return['order'] = $order;
        $return['order_goods_list'] = $order_goods_list;
        return $this->success($return);
    }

    //下单
    public function takeOrder() {
        $user = $this->_user;
        $param = $this->_param;
        $time = time();
        $type = 1;
        //获取地址信息
        $address = [
            'region' => $param['region'],//国家、地区
            'first_name' => $param['first_name'],
            'last_name' => $param['last_name'],
            'company' => $param['company'],
            'address' => $param['address'],
            'apartment' => $param['apartment'],
            'city' => $param['city'],
            'state' => $param['state'],
            'zip_code' => $param['zip_code'],
            'phone' => $param['phone'],
            'create_time' => $time
        ];
        //查询购物车数据
        if($user['is_wholesale'] == 1) {
            $type = 2;
            //批发商
            $goods_list = Db::name("shopping_trolley")->alias('a')
                ->field("a.goods_id,a.num,b.*,b.wholesale_price money")
                ->leftJoin('goods b','a.goods_id=b.id')
                ->where(['a.user_id'=>$user['id'],'a.deleted'=>0])->select()->toArray();

        }else {
            //普通用户
            $goods_list = Db::name("shopping_trolley")->alias('a')
                ->field("a.goods_id,a.num,b.*,b.price money")
                ->leftJoin('goods b','a.goods_id=b.id')
                ->where(['a.user_id'=>$user['id'],'a.deleted'=>0])->select()->toArray();
        }

        $weight = 0;//kg
        $pay_money = 0;
        $num = 0;
        foreach ($goods_list as $k=>$v) {
            if($v['stock'] < $v['num']) {
                return $this->error($v['name']." understock");
            }
            //计算重量-运费
            $weight = $weight + $v['weight']*$v['num'];
            //计算金额
            $pay_money = $pay_money + $v['money']*$v['num'];
            //计算数量
            $num = $num + $v['num'];
        }
        //运费
        $freight = Db::name('freight')->where('weight','<',$weight)->where(['deleted'=>0])->limit(1)->order('weight desc')->value("money");
        $total_money = $pay_money + $freight;

        $order = [
            'origin' => 1,
            'out_trade_no' => getOrderNo(),
            'take_no' => getTakeNo(),
            'money' => $total_money,
            'delivery_money' => $freight,
            'received_name' => '',//收货人
            'received_address' => '',//收货地址
            'received_tel' => '',//收货人联系方式
            'user_note' => '',//用户订单备注
            'state' => 1,//订单状态 1未付款,2已付款,3已接单,4配送中/待取货,5已收货,6已评价,7已取消,8.拒单，9申请退款,10已退款，11退款拒绝
            'user_id' => $user['id'],
            'create_time' => $time,
            'update_time' => $time,
        ];
        //开启事务
        Db::startTrans();
        try {
            $address_log_id = Db::name('address_log')->insertGetId($address);
            $order['address_log_id'] = $address_log_id;
            $order_id = Db::name('order')->insertGetId($order);
            //商品处理
            foreach ($goods_list as $k=>$v) {
                $order_goods_list[] = [
                    'order_id' => $order_id,
                    'goods_id' => $v['goods_id'],
                    'name' => $v['name'],
                    'icon' => $v[''],
                    'price' => $v['money'],
                    'num' => $v['num'],
                    'money' => $v['money'] * $v['num'],
                    'type' => $type,
                    'create_time' => $time,
                    'update_time' => $time,
                ];
                Db::name('goods')->where(['id'=>$v['id']])->dec('stock',$v['num'])->inc('salesNum',$v['num'])->update();
            }
            $res = Db::name('order_goods')->insertAll($order_goods_list);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $this->success($res);
    }

    //订单支付
    public function payOrder1() {
        //调起支付
    }

    //支付
    public function payOrder()
    {
        $user = $this->_user;
        if ($user['id']!=1){
            return $this->error("Under development, stay tuned");
        }
        //AW_K7gDVzvGAw1Hk9dJD3pXza486UAtYDuw0gTW8_c3L5PCaWEO8jz_JHnHJGgsnh6lqYlvBJyxlcb4c
        //EEPatvb25Afv_uKNdpV4n4k2zR3fqI3OL_K0-iZoQCpdvVsmKvkMP0D2hzXfufpJ6Jj9xw65cJEj1bWi
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                "AW_K7gDVzvGAw1Hk9dJD3pXza486UAtYDuw0gTW8_c3L5PCaWEO8jz_JHnHJGgsnh6lqYlvBJyxlcb4c",
            "EEPatvb25Afv_uKNdpV4n4k2zR3fqI3OL_K0-iZoQCpdvVsmKvkMP0D2hzXfufpJ6Jj9xw65cJEj1bWi"
//                'AfOVF7P3q1cOdgw7WnjJQlnY3OhmJriT3YDuOEA7s-lI-2tT9cxlCXEXPdgQojlG67gGSpuS4h4BzZWr',     // ClientID
//                'EIBqhkL6ysesyxZqwD3AG9dm0mPNjfoket9MhkFSRFk5WRxpFTWfpjFlsRROhH8LKOIyYSzqyRF0HtyK'      // ClientSecret
            )
        );
        /*sandbox 模式*/
        $apiContext->setConfig(array('mode' => 'live'));


        $payer = new \PayPal\Api\Payer();
        $payer->setPaymentMethod('paypal');

        $amount = new \PayPal\Api\Amount();
        $amount->setTotal('0.01');
        $amount->setCurrency('USD');

        $transaction = new \PayPal\Api\Transaction();
        $transaction->setAmount($amount);

        $redirectUrls = new \PayPal\Api\RedirectUrls();
        $sn=time();
        $redirectUrls->setReturnUrl("https://hawkmatic.shop/index/paypal/returnUrl/sn/".$sn)
            ->setCancelUrl("https://hawkmatic.shop/index/paypal/cancelUrl/sn/".$sn);

        $payment = new \PayPal\Api\Payment();
        $payment->setIntent('sale')
            ->setPayer($payer)
            ->setTransactions(array($transaction))
            ->setRedirectUrls($redirectUrls);
        try {
            $payment->create($apiContext);
            $url=$payment->getApprovalLink();
            return $this->success($url);
//            echo "<br><a href='".$url."'>点击支付</a>\n";
        }
        catch (\PayPal\Exception\PayPalConnectionException $ex) {
            var_dump($ex);
            echo $ex->getData();
        }
    }

    //订单列表
    public function orderList() {
        $user = $this->_user;
        $orderList = Db::name('order')->where(['user_id'=>$user['id']])->select()->toArray();
        return $this->success($orderList);
    }

}
